package com.zx.controller;

import com.zx.common.ResponseCode;
import com.zx.entity.Message;
import com.zx.entity.News;
import com.zx.repository.MessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private MessageRepository messageRepository;

    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "0") Integer page,
                             @RequestParam(value = "size", defaultValue = "2") Integer size,
                             Map<String, Object> map) {
        PageRequest request = PageRequest.of(page, size);
        Page<Message> messages = messageRepository.findAll(request);
        map.put("messages", messages);
        return new ModelAndView("message/list", map);
    }
    //删除留言
    @GetMapping("/delete/{messageId}")
    public ModelAndView delete(@PathVariable("messageId") Integer id,
                               Map<String,Object> map){
        Message message = messageRepository.getOne(id);
        messageRepository.delete(message);
        map.put("msg",ResponseCode.DELETE_SUCCESS.getDesc());
        map.put("url","/foodshare/message/list");
        return new ModelAndView("common/success",map);
    }
    @PostMapping("/saveMessage")
    public ModelAndView saveMessage(Message message,
                                    Map<String,Object> map,
                                    HttpSession session){
        if(session.getAttribute("loginUser")==null){
            map.put("msg",ResponseCode.NEED_LOGIN.getDesc());
            map.put("url","/foodshare/main/index");
            return new ModelAndView("common/error");
        }
        messageRepository.save(message);
        map.put("msg", ResponseCode.SAVE_SUCCESS.getDesc());
        map.put("url","/foodshare/main/index");
        return new ModelAndView("common/success");
    }
}
